package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.*;
import com.drcoffee.drcoffeemall.entry.erp.ErpOCC;
import com.drcoffee.drcoffeemall.feign.EnMallProviderClient;
import com.drcoffee.drcoffeemall.feign.ErpProviderClient;
import com.drcoffee.drcoffeemall.feign.OcmProviderClient;
import com.drcoffee.drcoffeemall.mapper.BsUserMapper;
import com.drcoffee.drcoffeemall.mapper.UserMapper;
import com.drcoffee.drcoffeemall.service.UserService;
import com.drcoffee.drcoffeemall.util.VerifyCodeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.*;

/*
 * 用户
 * */
@Service
@Transactional
//@DS("mysql")
@Slf4j
public class UserServiceImpl implements UserService {
    final
    UserMapper userMapper;
    final
    RedisTemplate<String, Object> redisTemplate;
    private final VerifyCodeUtil verifyCodeUtil;

    final
    BsUserMapper bsUserMapper;

    final
    private  ErpProviderClient erpProviderClient;

    final
    EnMallProviderClient enMallProviderClient;

    final
    OcmProviderClient ocmProviderClient;

    public UserServiceImpl(UserMapper userMapper, RedisTemplate<String, Object> redisTemplate, VerifyCodeUtil verifyCodeUtil, BsUserMapper bsUserMapper, OcmProviderClient ocmProviderClient, EnMallProviderClient enMallProviderClient, ErpProviderClient erpProviderClient) {
        this.userMapper = userMapper;
        this.redisTemplate = redisTemplate;
        this.verifyCodeUtil = verifyCodeUtil;
        this.bsUserMapper = bsUserMapper;
        this.ocmProviderClient = ocmProviderClient;
        this.enMallProviderClient = enMallProviderClient;
        this.erpProviderClient = erpProviderClient;
    }

    /*
     * 修改用户企业信息
     * */
    @Override
    public Map<String, Object> uploadUserFirm(User user) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            boolean result = userMapper.uploadUserFirm(user);
            resultMap.put("result", result);
            resultMap.put("message", "修改成功");
        } catch (Exception e) {
            resultMap.put("result", false);
            resultMap.put("message", "修改失败");
            resultMap.put("error", e.toString());
        }
        return resultMap;
    }


    /*
     * 添加邀请码
     * */
    @Override
    public Result addInvitation(InvitationCode invitationCode) {
        if (invitationCode.getErp_code().equals("552204001") && (invitationCode.getDiscount_one().compareTo(BigDecimal.ZERO) != 0 || invitationCode.getDiscount_two().compareTo(BigDecimal.ZERO) != 0)) {
            return new Result(3, "WARN", "该类用户无法设置折扣", null);
        }
        Integer existCountByErpCode = userMapper.getInvitationByErpCode(invitationCode.getErp_code());
        if (existCountByErpCode > 0) {
            return new Result(2, "WARN", "ERP编码已被注册", null);
        }
        while (true) {
            String code = VerifyCodeUtil.generateVerifyCode(6);
            Integer existCount = userMapper.getInvitationExistByCode(code);
            if (existCount == 0) {
                invitationCode.setCode(code);
                break;
            }
        }
        userMapper.addInvitation(invitationCode);
        return new Result(1, "SUCCESS", "", invitationCode.getCode());
    }

    @Override
    public ResponseEntity<Object> getInvitationCodeData(@RequestBody Map<String, Object> paramMap) {
        Integer currPage = (Integer) paramMap.get("currPage");
        Integer pageSize = (Integer) paramMap.get("pageSize");
        PageHelper.startPage(currPage, pageSize);
        List<Map<String, Object>> invitation_list = userMapper.getInvitationCodeData(paramMap);
        PageInfo<Map<String, Object>> resultData = new PageInfo<>(invitation_list);
        return new ResponseEntity<>(resultData, HttpStatus.OK);
    }

    /* 删除邀请码 */
    @Override
    public Result deleteInvitation(Integer id) {
        try {
            userMapper.deleteInvitation(id);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== deleteInvitation()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getFirmAlterByN() {
        try {
            List<FirmAlter> allFirmAlters = userMapper.getFirmAlterByN();
            return new Result(1, "SUCCESS", "", allFirmAlters);
        } catch (Exception e) {
            log.error("===================== getFirmAlterByN()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result setUserFirm(FirmAlter firmAlter) {
        try {
            userMapper.setUserFirm(firmAlter);
            userMapper.setFirmAlter(firmAlter);
            return new Result(1, "ERROR", "", null);
        } catch (Exception e) {
            log.error("===================== setUserFirm()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }


    /* 注册海外 */
//    @DS("enmysql")
    @Override
    public Result signinOverseasUser(User user) {
        try {
            enMallProviderClient.signinOverseasUser(user);
            //userMapper.signinOverseasUser(user);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== signinOverseasUser()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result getUserBySearch(Map<String, Object> val) {
        try {
            Integer currPage = (Integer) val.get("currPage");
            Integer pageSize = (Integer) val.get("pageSize");
            Integer permission_id = (Integer) val.get("permission_id");
            String search = "%" + (String) val.get("search") + "%";

            PageHelper.startPage(currPage, pageSize);
            PageInfo<User> userPage = new PageInfo<>(userMapper.getUserBySearch(permission_id, search));
            return new Result(1, "SUCCESS", "", userPage);
        } catch (Exception e) {
            log.error("===================== getUserBySearch()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    //    @DS("enmysql")
    @Override
    public Result getUserBySearchEN(Map<String, Object> val) {
        try {
            Integer currPage = (Integer) val.get("currPage");
            Integer pageSize = (Integer) val.get("pageSize");
            Integer permission_id = (Integer) val.get("permission_id");
            String search = (String) val.get("search");
            PageHelper.startPage(currPage, pageSize);
            List<User> userList;
            if (!Objects.equals(search, "")) {
                userList = userMapper.getUserBySearch(permission_id, "%" + search + "%");
            } else {
                userList = userMapper.getUserByPermission(permission_id);
            }
            PageInfo<User> userPage = new PageInfo<>(userList);
            return new Result(1, "SUCCESS", "", userPage);
        } catch (Exception e) {
            log.error("===================== getUserBySearchEN()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /* 调整折扣率 */
    @Override
    public Result setUserDiscount(String token, String account, Double one, Double two) {
        try {
            BsUser bs_user = (BsUser) redisTemplate.opsForValue().get(token);
            User mall_user = userMapper.getUserByAccount(account);
            if (mall_user == null || mall_user.getPermission_id() != 1) {
                return new Result(-1, "ERROR", "操作失败", null);
            }
            userMapper.setUserDiscount(account, one, two);
            bsUserMapper.putOperationRecord(bs_user.getUsername(), "调整用户：\"" + account + "\"的一级折扣为\"" + one + "\"，二级折扣为\"" + two + "\"");
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== setUserDiscount()异常： =====================", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /*
     * 查询用户反馈信息
     * */
    @Override
    public Result getFeedbackByCn() {
        try {
            List<Feedback> feedbackList = userMapper.getFeedback();
            return new Result(1, "SUCCESS", "", feedbackList);
        } catch (Exception e) {
            log.error("===================== getFeedback()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
//    @DS("enmysql")
    public Result getFeedbackByEn() {
        try {
            List<Feedback> feedbackList = userMapper.getFeedback();
            return new Result(1, "SUCCESS", "", feedbackList);
        } catch (Exception e) {
            log.error("===================== getFeedback()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result outFeedback(Integer id) {
        try {
            userMapper.outFeedback(id);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== outFeedback()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    public Result getByAccount(String account) {
        try {
            List<User> list = userMapper.getByAccount(account);
            return new Result(1, "SUCCESS", "", list);
        } catch (Exception e) {
            log.error("===================== getByAccount()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public ResponseEntity<Object> checkErpCode(Map<String, Object> paramMap) {
        Map<String, Object> resultMap = ocmProviderClient.checkErpCode(paramMap);
        return new ResponseEntity<>(resultMap, HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> getUserData(Map<String, Object> paramMap) {
        Integer currPage = (Integer) paramMap.get("currPage");
        Integer pageSize = (Integer) paramMap.get("pageSize");
        PageHelper.startPage(currPage, pageSize);
        PageInfo<Map<String, Object>> resultData = null;
        if (paramMap.get("permission_id") != null && (Integer) paramMap.get("permission_id") == 2) {
            resultData = enMallProviderClient.getUserData(paramMap);
        } else {
            List<Map<String, Object>> invitation_list = userMapper.getUserData(paramMap);
            resultData = new PageInfo<>(invitation_list);
        }
        return new ResponseEntity<>(resultData, HttpStatus.OK);
    }

    @Override
    public  int getCode(String company) {
        ErpOCC erpOCC = erpProviderClient.getCode(company);
        if (erpOCC==null){
            return 0;
        }
        int  ss = ocmProviderClient.insert(erpOCC);
        return ss;
    }


}
